package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.healthy.HealthyDataActivity;
import com.shwread.android.qysw.activity.healthy.HealthyFriendPKActivity;
import com.shwread.android.qysw.activity.healthy.HealthyMyGoalStepActivity;
import com.shwread.android.qysw.activity.healthy.HealthyRankActivity;
import com.shwread.android.qysw.activity.healthy.MyIntegralActivity;
import com.shwread.android.qysw.step.StepService;
import com.shwread.android.qysw.step.UserStepModel;
import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.api.MyNoLoadAsynctask;
import com.shwread.android.qysw.step.dto.HMRank;
import com.shwread.android.qysw.step.dto.HMRankDto;
import com.shwread.android.qysw.step.dto.HMUserInfoDto;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.AlertHelper;
import com.shwread.android.qysw.step.view.RectImageView;
import com.shwread.android.qysw.tools.Screen;
import com.shwread.android.qysw10000182.R;
import com.squareup.picasso.Picasso;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import base.tina.core.task.infc.ITaskResult;
import logic.constants.AppConfig;
import logic.constants.Const;

/**
 * Created by Fantasy on 16/3/27.
 */
public class MyHealthyPage extends AbstractUIPage<MainActivity> implements View.OnClickListener {

    public static MyHealthyPage instance;

    protected Context context;
    ImageView integraButton;
    ImageView goalButton;
    RelativeLayout goalFinishLayout;
    TextView todayStepText;
    TextView todayKmText;
    TextView todayGoalText;
    TextView todayCalories;
    RelativeLayout inviteFriendPk;
    LinearLayout mailListLayout;
    LinearLayout homeListviewLayout;
    TextView goalFinishText;
    TextView todayGoalTextRight;
    SwipeRefreshLayout refreshLayout;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private Handler mHandler;
    protected static final int UPDATE_TEXT = 0;
    protected static final int UPLOAD = 1;
    private Timer mSecTimer;
    private TimerTask mSecTimerTask;
    private int beforeThisStep = 0;//记录ui更新的前一次步数
    private int limitStep = 25;//10秒内超过25步不计入步数
    private int beforeThisStep1 = 0;//提交数据的前一次步数
    private int limitStep1 = 50;//20秒内超过50步不计入步数
    //手机传感器管理器，用来管理所有的传感器
    private SensorManager sensorManager;

    public MyHealthyPage(MainActivity mainActivity) {
        super(mainActivity);
    }

    public static MyHealthyPage getInstance(MainActivity t) {
        if (instance == null) instance = new MyHealthyPage(t);
        return instance;
    }

    @Override
    public <E extends Activity> View createView(E e, int i) {

        curMyView = bActivity.getLayoutInflater().inflate(R.layout.fragment_healthy, null);
        setListeners();
        setView();
        beforeThisStep = UserStepModel.getInstance().getUserTodayStep();
        beforeThisStep1 = UserStepModel.getInstance().getUserTodayStep();
        //得到SensorManager对象
        sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
        List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
        //迭代输出获得上的传感器
        for (Sensor sensor : sensors) {
            if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                UserHealthyModel.getInstance().setHasSensor();
                Log.i("Sensor---->", sensor.getName().toString());
            }
        }
        mTimer = new Timer();
        mSecTimer = new Timer();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case UPDATE_TEXT:
                        if(UserStepModel.getInstance().getUserTodayStep() - beforeThisStep > limitStep) {
                            StepService.setStep(beforeThisStep);
                            return;
                        }
                        todayStepText.setText(UserStepModel.getInstance().getUserTodayStep() + "步");
                        DecimalFormat df = new DecimalFormat("#0.0");
                        todayKmText.setText(df.format(UserStepModel.getInstance().getUserTodayDistance()) + "KM");
                        todayCalories.setText(df.format(UserStepModel.getInstance().getUserTodayCalories()) + "");
                        if (UserHealthyModel.getInstance().getMyHmUserInfo().getTarget() > 0 && System.currentTimeMillis() < UserHealthyModel.getInstance().getMyHmUserInfo().getTargetEnd()) {
                            todayGoalText.setText(UserHealthyModel.getInstance().getMyHmUserInfo().getTarget() + "");
                        } else {
                            todayGoalText.setText("0");
                        }
                        beforeThisStep = UserStepModel.getInstance().getUserTodayStep();
                        break;
                    case UPLOAD:
                        if(UserStepModel.getInstance().getUserTodayStep() - beforeThisStep1 > limitStep1) {
                            StepService.setStep(beforeThisStep1);
                            return;
                        }
                        updateUserSteps();
                        beforeThisStep1 = UserStepModel.getInstance().getUserTodayStep();
                        break;
                }
            }
        };

        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                mHandler.sendEmptyMessage(UPDATE_TEXT);
            }
        };

        mTimer.schedule(mTimerTask, 10000, 1000);

        mSecTimerTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(UPLOAD);
            }
        };
        mSecTimer.schedule(mSecTimerTask, 20000, 20000);
        refreshLayout = (SwipeRefreshLayout) curMyView.findViewById(R.id.refresh_layout);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshLayout.setRefreshing(false);
                updateUserSteps();
            }
        });

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("phoneNum", Const.phone_number);
        params.put("enterpriseId", AppConfig.getEnterpriseId());
        HashMap<String, String> urlMap = new HashMap<>();
        urlMap.put("url", "/hzlqswserver/health/userInfo");
        MyAsynctask myAsynctask = new MyAsynctask(getContext(), new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                Log.i("darren", result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("returnObject");
                    HMUserInfoDto hmUserInfoDto = HMUserInfoDto.parserJson(res);
                    Log.i("darrens", "target:" + hmUserInfoDto.getHMUserInfo().getTarget());
                    boolean b = hmUserInfoDto.getHMUserInfo().getTarget() > 0;
                    Log.i("darrens", "target:" + b);
                    if (hmUserInfoDto.getHMUserInfo().getTarget() > 0 && (System.currentTimeMillis() < hmUserInfoDto.getHMUserInfo().getTargetEnd() || hmUserInfoDto.getHMUserInfo().getTargetEnd() == 0)) {
                        todayGoalText.setText(hmUserInfoDto.getHMUserInfo().getTarget() + "");
                    } else {
                        todayGoalText.setText("0");
                    }
                    UserHealthyModel.getInstance().setMyHmUserInfo(hmUserInfoDto.getHMUserInfo());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                homeListviewLayout.removeAllViews();
                String myUrl = "hzlqswserver/health/rank";
                HashMap<String, String> hashMapUrl = new HashMap<>();
                hashMapUrl.put("url", myUrl);
                HashMap<String, String> params = new HashMap<>();
                params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
                params.put("enterpriseId", AppConfig.getEnterpriseId());
                params.put("page", "1");
                params.put("pageSize", "5");
                MyNoLoadAsynctask myAsynctask = new MyNoLoadAsynctask(getContext(), new MyNoLoadAsynctask.RequestListener() {
                    @Override
                    public void requestSuccess(String result) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(result);
                            String res = jsonObject.optString("returnObject");

                            Log.i("darren2", res);
                            HMRankDto hmRankDto = HMRankDto.parserJson(res);
                            List<HMRank> hmRankList = hmRankDto.getData_list();
                            for (int i = 0; i < hmRankList.size(); i++) {
                                HMRank hmRank = hmRankList.get(i);
                                View view = View.inflate(getContext(), R.layout.healthy_other_user_grade_item, null);
                                TextView numTextView = (TextView) view.findViewById(R.id.number_text);
                                numTextView.setText(hmRank.getSort() + "");
                                RectImageView headIconImg = (RectImageView) view.findViewById(R.id.head_icon_img);
                                if (!TextUtils.isEmpty(hmRank.getUserHead())) {
                                    Picasso.with(getContext()).load(hmRank.getUserHead()).into(headIconImg);
                                }
                                TextView nameText = (TextView) view.findViewById(R.id.name_text);
                                nameText.setText(hmRank.getNickName());
                                TextView stepCountText = (TextView) view.findViewById(R.id.step_count_text);
                                stepCountText.setText(hmRank.getStep() + "");
                                homeListviewLayout.addView(view);
                                upDateHealthyInfo();
                            }
                            int needHeight = Screen.dip2px(60)*hmRankList.size();
                            Log.i("darren","height:"+needHeight+"");
                            homeListviewLayout.setMinimumHeight(needHeight);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                myAsynctask.execute(hashMapUrl, params);
            }


        });
        myAsynctask.execute(urlMap, params);
        return curMyView;
    }
    public void setView() {
        todayStepText = (TextView) curMyView.findViewById(R.id.today_step_text);
        todayStepText.setText(UserStepModel.getInstance().getUserTodayStep() + "步");
        goalFinishLayout = (RelativeLayout) curMyView.findViewById(R.id.goal_finish_layout);
        goalFinishText = (TextView) curMyView.findViewById(R.id.goal_finish_text);
        todayKmText = (TextView) curMyView.findViewById(R.id.today_km_text);
        DecimalFormat df = new DecimalFormat("#0.0");
        todayKmText.setText(df.format(UserStepModel.getInstance().getUserTodayDistance()) + "KM");
        todayGoalText = (TextView) curMyView.findViewById(R.id.today_goal_text);
        todayGoalTextRight = (TextView) curMyView.findViewById(R.id.today_goal_text_right);

        todayCalories = (TextView) curMyView.findViewById(R.id.today_calories);
        todayCalories.setText(df.format(UserStepModel.getInstance().getUserTodayCalories()) + "");
        homeListviewLayout = (LinearLayout) curMyView.findViewById(R.id.home_listview_layout);
        todayGoalText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentee = new Intent(getContext(), HealthyMyGoalStepActivity.class);
                getContext().startActivity(intentee);
            }
        });
        todayStepText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent goDataIntent = new Intent(getContext(), HealthyDataActivity.class);
                getContext().startActivity(goDataIntent);
            }
        });


        final RelativeLayout redPackageView = (RelativeLayout) curMyView.findViewById(R.id.red_package_layout);
        ImageView closeImg = (ImageView) curMyView.findViewById(R.id.close_red_package);
        ImageView center_red_package = (ImageView) curMyView.findViewById(R.id.center_red_package);
        Date date = new Date();
        Log.i("darren", "hour:" + date.getHours());
        if (UserStepModel.getInstance().getUserTodayStep() >= 5000 && !UserStepModel.getInstance().isHasGetRedPackage() && date.getHours() >= 22) {
            redPackageView.setVisibility(View.VISIBLE);
            goalFinishText.setText("您的今日步数达到5000步，您有一个积分礼包未领取”");
            center_red_package.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getScoreAPI();
                    redPackageView.setVisibility(View.INVISIBLE);
                }
            });
            closeImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    redPackageView.setVisibility(View.INVISIBLE);
                }
            });
        } else {
            if (UserStepModel.getInstance().getUserTodayStep() < 5000) {
                goalFinishLayout.setVisibility(View.INVISIBLE);
            } else {
                goalFinishText.setText("您的今日步数达到5000步，已领取今日积分。");
            }
        }
    }

    public void upDateHealthyInfo() {
        DecimalFormat df = new DecimalFormat("#0.0");
        String h_url = "hzlqswserver/health/updateHealthInfo";
        HashMap<String, String> hashMapUrl = new HashMap<>();
        hashMapUrl.put("url", h_url);
        HashMap<String, String> h_params = new HashMap<>();
        h_params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
        h_params.put("enterpriseId", AppConfig.getEnterpriseId());
        h_params.put("todayStep", UserStepModel.getInstance().getUserTodayStep() + "");
        h_params.put("todayMileage", df.format(UserStepModel.getInstance().getUserTodayDistance()));
        h_params.put("todayCalorie", df.format(UserStepModel.getInstance().getUserTodayCalories()));
        h_params.put("dailyStep", UserStepModel.getInstance().getUserTodayStep() + "");
        MyNoLoadAsynctask myAsynctaskUpdate = new MyNoLoadAsynctask(getContext(), new MyNoLoadAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {

            }
        });
        myAsynctaskUpdate.execute(hashMapUrl, h_params);
    }

    public void getScoreAPI() {
        String h_url = "hzlqswserver/health/getDailyScore";
        HashMap<String, String> hashMapUrl = new HashMap<>();
        hashMapUrl.put("url", h_url);
        HashMap<String, String> h_params = new HashMap<>();
        h_params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
        h_params.put("enterpriseId", AppConfig.getEnterpriseId());
        MyAsynctask myAsynctaskgetScore = new MyAsynctask(getContext(), new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                UserStepModel.getInstance().updateRedPackage();
                Toast.makeText(getContext(), "获取积分成功", Toast.LENGTH_LONG).show();
                goalFinishText.setText("您的今日步数达到5000步，已领取今日积分。");
            }
        });
        myAsynctaskgetScore.execute(hashMapUrl, h_params);
    }

    public void setListeners() {
        integraButton = (ImageView) curMyView.findViewById(R.id.integra_button);
        integraButton.setOnClickListener(this);
        goalButton = (ImageView) curMyView.findViewById(R.id.goal_button);
        goalButton.setOnClickListener(this);
        inviteFriendPk = (RelativeLayout) curMyView.findViewById(R.id.invite_friend_pk);
        inviteFriendPk.setOnClickListener(this);
        mailListLayout = (LinearLayout) curMyView.findViewById(R.id.mail_list_layout);
        mailListLayout.setOnClickListener(this);
    }

    @Override
    public View updateView(int i, ITaskResult iTaskResult) {

        return null;
    }

    @Override
    public void notifyView(int i, Bundle bundle) {

    }

    @Override
    public int enter(IUIPage<?> iuiPage) {
        Log.i("darren", "enter");
        if (!UserHealthyModel.getInstance().getHasSensor()) {
            showNoSensorDialog();
        }
        if (UserHealthyModel.getInstance().isFirstUse() && UserHealthyModel.getInstance().getHasSensor()) {
            //showStartStepDialog();
            Toast.makeText(getContext(), "记步功能已经同步开启", Toast.LENGTH_LONG).show();
            UserHealthyModel.getInstance().setIsFirstUse(false);
        }
        return 0;
    }

    @Override
    public int leave(IUIPage<?> iuiPage) {
        return 0;
    }

    @Override
    public void setStatus(int i) {

    }

    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.integra_button:
                Intent intentNum = new Intent(getContext(), MyIntegralActivity.class);
                getContext().startActivity(intentNum);
                break;
            case R.id.goal_button:
                Intent intent = new Intent(getContext(), HealthyMyGoalStepActivity.class);
                getContext().startActivity(intent);
                break;
            case R.id.invite_friend_pk:
                Intent intentPk = new Intent(getContext(), HealthyFriendPKActivity.class);
                getContext().startActivity(intentPk);
                break;
            case R.id.mail_list_layout:
                Intent intentRank = new Intent(getContext(), HealthyRankActivity.class);
                getContext().startActivity(intentRank);
                break;
            case R.id.today_goal_text:
                Intent intentee = new Intent(getContext(), HealthyMyGoalStepActivity.class);
                getContext().startActivity(intentee);
                break;
        }
    }

    private void showNoSensorDialog() {
        AlertHelper.AlertParams alertParams = new AlertHelper.AlertParams();
        alertParams.setMessage("当前手机不支持记步功能");
        alertParams.setConfirmString("不再提醒");
        alertParams.setCancelString("取消");
        UserHealthyModel.getInstance().setHasSensor();
        alertParams.setConfirmListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UserHealthyModel.getInstance().setHasSensor();
                dialog.dismiss();
            }
        });
        alertParams.setCancelListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertHelper.showAlert(getContext(), alertParams);
    }

    private void showStartStepDialog() {
        AlertHelper.AlertParams alertParams = new AlertHelper.AlertParams();
        alertParams.setMessage("记步功能已经同步开启");
        alertParams.setConfirmString("不再提醒");
        alertParams.setCancelString("取消");
        UserHealthyModel.getInstance().setHasSensor();
        alertParams.setConfirmListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                UserHealthyModel.getInstance().setIsFirstUse(false);
                dialog.dismiss();
            }
        });
        alertParams.setCancelListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertHelper.showAlert(getContext(), alertParams);
    }

    private void updateUserSteps() {
        if (UserHealthyModel.getInstance().getMyHmUserInfo() != null) {
            upDateHealthyInfo();
            homeListviewLayout.removeAllViews();
            String myUrl = "hzlqswserver/health/rank";
            HashMap<String, String> hashMapUrl = new HashMap<>();
            hashMapUrl.put("url", myUrl);
            HashMap<String, String> params = new HashMap<>();
            params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
            params.put("enterpriseId", AppConfig.getEnterpriseId());
            params.put("page", "1");
            params.put("pageSize", "5");
            MyNoLoadAsynctask myAsynctask = new MyNoLoadAsynctask(getContext(), new MyNoLoadAsynctask.RequestListener() {
                @Override
                public void requestSuccess(String result) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        String res = jsonObject.optString("returnObject");

                        Log.i("darren2", res);
                        HMRankDto hmRankDto = HMRankDto.parserJson(res);
                        List<HMRank> hmRankList = hmRankDto.getData_list();
                        for (int i = 0; i < hmRankList.size(); i++) {
                            HMRank hmRank = hmRankList.get(i);
                            View view = View.inflate(getContext(), R.layout.healthy_other_user_grade_item, null);
                            TextView numTextView = (TextView) view.findViewById(R.id.number_text);
                            numTextView.setText(hmRank.getSort() + "");
                            RectImageView headIconImg = (RectImageView) view.findViewById(R.id.head_icon_img);
                            if (!TextUtils.isEmpty(hmRank.getUserHead())) {
                                Picasso.with(getContext()).load(hmRank.getUserHead()).into(headIconImg);
                            }
                            TextView nameText = (TextView) view.findViewById(R.id.name_text);
                            nameText.setText(hmRank.getNickName());
                            TextView stepCountText = (TextView) view.findViewById(R.id.step_count_text);
                            stepCountText.setText(hmRank.getStep() + "");
                            homeListviewLayout.addView(view);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            myAsynctask.execute(hashMapUrl, params);
        }
    }
}
